package com.aos.erp.common.web.wrapper;


import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

public class RequestWrapper extends HttpServletRequestWrapper {
    /**
     * 自定义参数map
     */
    private Map<String, String[]> params = new HashMap<>();

    public RequestWrapper(HttpServletRequest request) {
        //super中已经判断了request非空
        super(request);
        //复制参数
        params.putAll(request.getParameterMap());
    }

    /**
     * 重写getParameter，代表参数从当前类中的map获取
     *
     * @param name
     * @return 如果有多个值，只返回第0个
     */
    @Override
    public String getParameter(String name) {
        Assert.hasText(name, "获取request参数，参数名不能为空");
        String[] values = params.get(name);
        if (values != null) {
            if (values.length == 0) {
                return "";
            }
            return values[0];
        } else {
            return null;
        }
    }

    /**
     * 同上
     *
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        Assert.hasText(name, "获取request参数，参数名不能为空");
        return params.get(name);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        Vector<String> vector = new Vector<>(params.keySet());
        return vector.elements();
    }

    /**
     * 添加参数
     *
     * @param name
     * @param value
     */
    public void addParameter(String name, Object value) {
        Assert.hasText(name, "向request添加参数，参数名不能为空");
        if (null == value) {
            params.put(name, null);
        } else if (value instanceof String[]) {
            params.put(name, (String[]) value);
        } else if (value instanceof String) {
            params.put(name, new String[]{(String) value});
        } else {
            params.put(name, new String[]{String.valueOf(value)});
        }
    }
}